<script>
import { noop } from 'lodash'

export default {
  name: 'ZlstAsyncSelect',
  data() {
    return {
      $scrollbar: null,
      $scrollbarUl: null
    }
  },
  beforeDestroy() {
    if (this.$scrollbar) {
      this.$scrollbar.removeEventListener('scroll', this.handleScrollToBottom, false)
    }
  },
  methods: {
    handleSelectDropdown() {
      let target
      const traverse = parent => {
        if (parent.$options.name === 'ElSelectDropdown') {
          target = parent.$el
        } else {
          parent.$children.forEach(traverse)
        }
      }
      traverse(this)
      if (!target) {
        return false
      }
      this.$scrollbar = target.querySelector('.el-select-dropdown__wrap')
      this.$scrollbarUl = this.$scrollbar.querySelector('.el-select-dropdown__list')
      this.$scrollbar.addEventListener('scroll', this.handleScrollToBottom, false)
    },
    handleScrollToBottom(evt) {
      if (evt.target.scrollTop + evt.target.offsetHeight === this.$scrollbarUl.offsetHeight) {
        this.$emit('scroll-to-bottom')
      }
    }
  },
  render() {
    return (
      <el-select
        {...{
          attrs: this.$attrs,
          on: {
            ...this.$listeners,
            'visible-change': toggle => {
              const func = this.$listeners['visible-change'] || noop
              func(toggle)
              if (toggle && !this.$scrollbar) {
                this.handleSelectDropdown()
              }
            }
          },
          scopedSlots: this.$scopedSlots
        }}
      />
    )
  }
}
</script>
